<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<link href="../../component/layui/css/layui.css" rel="stylesheet" />
		<link href="../../admin/css/pearCommon.css" rel="stylesheet" />
	</head>
	<body>
		<body class="pear-container">
		    <div class="layui-card">
		        <div class="layui-card-body">
		            <form class="layui-form" action="">
		                <div class="layui-form-item">
		                    <label class="layui-form-label">要素名称</label>
							<div class="layui-input-inline">
								<input class="layui-input" id="demoReload"  name="elementName" placeholder="" type="text">
							</div>
							<a class="pear-btn pear-btn-md pear-btn-primary" data-type="reload" id="featureSearch" lay-filter="user-query" lay-submit>
								<i class="layui-icon layui-icon-search"></i>
								查询
							</a>
		                    <button type="button" class="pear-btn pear-btn-md"  id="featureReset">
		                        <i class="layui-icon layui-icon-refresh"></i>
		                        重置
		                    </button>
		                </div>
		            </form>
		        </div>
		    </div>
		    <div class="layui-card">
		        <div class="layui-card-body">
		            <table id="user-table" lay-filter="user-table"></table>
		        </div>
		    </div>
		</body>

		<script type="text/html" id="user-toolbar">
		    <button class="pear-btn pear-btn-primary pear-btn-md" lay-event="add">
		        <i class="layui-icon layui-icon-add-1"></i>
		        添加要素
		    </button>
		    <button class="pear-btn pear-btn-danger pear-btn-md" lay-event="batchRemove">
		        <i class="layui-icon layui-icon-delete"></i>
		        删除
		    </button>
		</script>

		<script type="text/html" id="user-sex">
			{{#if (d.sex == 1) { }}
			<span>男</span>
			{{# }else if(d.sex == 2){ }}
			<span>女</span>
			{{# } }}
		</script>

		<script type="text/html" id="user-bar">
			<input type="checkbox" name="状态" valueId="{{d.id}}" valueElementName="{{d.elementName}}"  valueServiceType="{{d.serviceType}}" lay-skin="switch" lay-text="启用|禁用" lay-filter="enabledState" {{ d.status == "1" ? "checked" : "" }}>
			<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="detail">预览</a>
			<a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
			<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
		</script>

		<script type="text/html" id="user-enable">
			<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="start">启用</a>
		</script>
		<script id="data-type" type="text/html">
			{{#if (d.serviceType == 1) { }}
			<span>3dTiles</span>
			{{# }else if(d.serviceType == 2){ }}
			<span>geoJson</span>
			{{# }else if(d.serviceType == 3){ }}
			<span>wms</span>
			{{# }else if(d.serviceType == 4){ }}
			<span>wfs</span>
			{{# } }}
		</script>
		<script id="createTime-type" type="text/html">
			<div>{{ layui.util.toDateString(d.createTime, 'yyyy-MM-dd HH:mm:ss') }}</div>
		</script>
		<script id="service-status" type="text/html">
			{{#if (d.status == 1) { }}
			<span style="color: #338528;">启用</span>
			{{# }else if(d.status == 0){ }}
			<span>禁用</span>
			{{# } }}
		</script>
		<!--		新增开始 -->
		<div class="site-text"  style="margin: 5%; display: none" id="service-window"  target="test123">
			<form class="layui-form"  id="fm" action="" enctype="multipart/form-data">
				<div class="layui-form-item">
					<label class="layui-form-label">要素名称</label>
					<div class="layui-input-block">
						<input type="text" id="elementName" name="elementName" required  lay-verify="required" placeholder="请输入要素名称" maxlength="50" autocomplete="off" class="layui-input">
						<input type="hidden" id="status" name="status" value="1">
						<div class="layui-form-mid layui-word-aux">必填项</div>
					</div>
				</div>
				<div class="layui-form-item" id="service-type">
					<label class="layui-form-label">要素类型</label>
					<div class="layui-input-block">
						<select name="serviceType" id="serviceType" lay-verify="required">
							<option value=""></option>
<!--							<option value="1">3dTiles</option>-->
<!--							<option value="2">geoJson</option>-->
<!--							<option value="3">wms</option>-->
							<option value="4">wfs</option>
						</select>
						<div class="layui-form-mid layui-word-aux">必填项</div>
					</div>
				</div>
				<div class="layui-form-item" id="service-address">
					<label class="layui-form-label">上传shp压缩包</label>
					<div class="layui-input-block">
						<button type="button" class="layui-btn layui-btn-primary" id="file" name="file"><i class="layui-icon"></i>只允许上传zip压缩文件</button>
						<div class="layui-form-mid layui-word-aux">必填项 *请确保单个ZIP文件中有且只有一个（或一组完整的）可识别类型的文件</div>
					</div>
				</div>
				<div class="layui-form-item">
					<label class="layui-form-label">要素描述</label>
					<div class="layui-input-block">
						<textarea name="remark" id="remark" placeholder="请输入要素描述" maxlength="200" class="layui-textarea"></textarea>
					</div>
				</div>
			</form>

		</div>
		<!--		新增结束 -->
		<script src="../../component/layui/layui.js"></script>
		<script>
			var cumstomObj = {};
			var chooseFlag =false;
			function loginStatusIntercept(e){
                console.log(e);
                layer.msg(e);
                setTimeout(()=>{
                    top.location.href = "/ftwgypt/login"
                },3000)
            }
			function json_to_get(sstr ){

				sstr = sstr.replace(/\t/g,"");
				sstr = sstr.replace(/\"/g,"").replace("{","").replace("}","");
				sstr = sstr.replace(",","&").replace(":","=");
				sstr = sstr.replace(/\"/g,"").replace(/{/g,"").replace(/}/g,"")
				sstr= sstr.replace(/,/g,"&").replace(/:/g,"=");
				return sstr;
			}
		    layui.use(['table','form','jquery','upload'],function () {
		        let table = layui.table;
		        let form = layui.form;
		        let $ = layui.jquery;
				let upload = layui.upload;
				let postUrl = '/one/element/local';

		        let MODULE_PATH = "/system/custom/";

		        let cols = [
		            [
		                {type:'checkbox'},
		                // {title: '缩略图', field: 'username', align:'center', width:100},
						{title: '要素名称', field: 'elementName', align:'center'},
		                {title: '要素描述', field: 'remark', align:'center'},
						{title: '要素格式', field: 'serviceType', align:'center', templet:'#data-type'},
						{title: '要素状态', field: 'status',sort: true,  align:'center', templet:'#service-status'},
						{title: '创建时间', field: 'createTime', sort: true,align:'center',templet:'#createTime-type'},
		                {title: '操作', toolbar: '#user-bar', fixed: 'right', align:'center', width:300}
		            ]
		        ];

		        table.render({
		            elem: '#user-table',
					url: '/one/element/local/list',
					method: 'post',
					contentType: 'application/json',
					where: {
						order: 3,
						orderDesc: 0
					},
					request: {
						pageName: 'pageNo' //页码的参数名称，默认：page
						,limitName: 'pageSize' //每页数据量的参数名，默认：limit
					},
					parseData: function(res){ //res 即为原始返回的数据
						if (res.errorCode === '401') {
							loginStatusIntercept(res.msg)
							return
						}else{
							return {
							"createTime": null,
							"createBy": null,
							"updateTime": null,
							"updateBy": null,
							"remark": null,
							"code": 200,
							"msg": "...",
							"count": res.data.total,
							"data":res.data.list
							}
						}
					},
					id: 'user-table',
		            page: true ,
		            cols: cols ,
		            skin: 'line',
		            toolbar: '#user-toolbar',
					response: {
						statusCode: 200 //成功的状态码，默认：0
					},
					initSort: {
						field: 'createTime',
						type: 'desc',
					},
		            defaultToolbar: [{
		                layEvent: 'refresh',
		                icon: 'layui-icon-refresh',
						title:'刷新'
		            }, 'filter']  // , 'print', 'exports'
		        });


				table.on('sort(user-table)', function(obj){ //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
					// console.log(obj.field); //当前排序的字段名
					// console.log(obj.type); //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）

					var field=obj.field;
					var type=obj.type;
					var order=1;
					var orderDesc=0;
					if(field==='createTime'){
						order=3;
					}else if(field==='updateTime'){
						order=2;
					}

					if(type==="asc"){
						orderDesc=1
					}else if(type=="desc"){
						orderDesc=0;
					}else{
						orderDesc=0;
						order=2;
					}


					//尽管我们的 table 自带排序功能，但并没有请求服务端。
					//有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
					table.reload('user-table', {
						initSort: obj //记录初始排序，如果不设的话，将无法标记表头的排序状态。 layui 2.1.1 新增参数
						,where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
							order: order //排序字段   在接口作为参数字段  field order
							,orderDesc: orderDesc //排序方式   在接口作为参数字段  field order
						}
					});
				});

		        table.on('tool(user-table)', function(obj){
					var data = obj.data;
					if(obj.event === 'detail'){
                        var elementUrl=" ";
						var jumpUrl=" ";
						// var pathname = top.location.href;
						var JUMP_PATH = window.sessionStorage.envLocation+"/jump.html";
						$.ajax({
							url: "/one/element/local/serviceInfo",
							type: "GET",
							data:{id:data.id},
							dataType: "json",
							success: function(res){
								if (res.errorCode === '401') {
									loginStatusIntercept(res.msg)
									return
								}
								if(res.success){
									elementUrl=res.data.url;
									jumpUrl=JUMP_PATH + '?url='+ elementUrl.substr(elementUrl.indexOf("geoserver")-1)+'&type='+data.serviceType;//url通过geoserver截断解决跨域问题
									window.open(jumpUrl);
								}else{
									layer.msg("预览失败,失败原因:"+res.msg, {icon: 5});
								}
							}
						});

		            } else if(obj.event === 'edit'){
						layer.open({
							type: 1,
							title: '修改业务要素',
							shade: 0.1,//遮罩透明度
							area: ['60%', '60%'],
							content: $('#service-window'),
							resize: true,
							btn: ['确定', '取消'],
							success:function(layero,index){
								$('#elementName').val(data.elementName);
								$('#service-type').hide();
								$('#service-address').hide();
								$('#remark').val(data.remark);
							},
							yes:function(index,layero){
								var elementName = $("#elementName").val();
								if(elementName == ''){
									layer.msg('要素名称不能为空',{icon:2,time:1000});
									return;
								}
								$.ajax({
									url: "/one/element/local",
									type: "PUT",
									data:JSON.stringify({
										elementName: $('#elementName').val(),
										remark: $('#remark').val(),
										id: data.id,
									}),
									dataType: "json",
									contentType: "application/json; charset=UTF-8",
									success: function(data){
										if (data.errorCode === '401') {
											loginStatusIntercept(data.msg)
											return
										}
										if(data.success){
											layer.alert('修改成功',{icon:1,title:'提示'},function(i){
												layer.close(i);
												layer.close(index);//关闭弹出层
												$("#fm")[0].reset()//重置form
											});
											table.reload('user-table',{//重载表格
												page:{
													curr:obj.curr
												}
											})
										}else{
											layer.msg("修改失败,失败原因:"+data.msg, {icon: 5});
										}
									}
								});
							}
						});

		            }else if(obj.event === 'del'){
						layer.confirm('确认删除？',{icon: 3, title:'提示'}, function(index){
							// console.log(data);
							let ids = data.id;
							$.ajax({
								url: "/one/element/localDel",
								type: "POST",
								data:{ids:ids},
								dataType: "json",
								success: function(data){
									if (data.errorCode === '401') {
										loginStatusIntercept(data.msg)
										return
									}
									if(data.success){
										//删除这一行
										obj.del();
										//关闭弹框
										layer.close(index);
										layer.msg("删除成功", {icon: 6});
									}else{
										layer.msg("删除失败", {icon: 5});
									}
								}
							});
						});
					}

		        });
				
				$("#demoReload").unbind("keydown").keydown(function (e) {//当按下按键时
					e.stopPropagation()
					var key = e.keyCode || e.charCode || e.which;
					if (key == 13) {
						e.preventDefault()
						$("#featureSearch").trigger('click');
					}
        		});

				$('#featureSearch').on('click', function(){
					var active = {
						reload: function(){
							var demoReload = $('#demoReload');
							//执行重载
							table.reload('user-table', {
								// url:'/one/element/origin/list',
								page: {
									curr: 1 //重新从第 1 页开始
								}
								// ,method: 'post'
								,where: {
									elementName: demoReload.val()
								}
							}, 'data');
						}
					};
					var type = $(this).data('type');
					active[type] ? active[type].call(this) : '';
				});


				$('#featureReset').on('click', function(){

							var demoReload = $('#demoReload');
					demoReload.val("")
							//执行重载
							table.reload('user-table', {
								// url:'/back/one/element/origin/list',
								page: {
									curr: 1 //重新从第 1 页开始
								}
								// ,method: 'post'
								,where: {
									elementName: demoReload.val()
								}
							}, 'data');


				});

		        table.on('toolbar(user-table)', function(obj){
		            if(obj.event === 'add'){
		                cumstomObj.add();
		            } else if(obj.event === 'refresh'){
		                cumstomObj.refresh();
		            } else if(obj.event === 'batchRemove'){
		                cumstomObj.batchRemove(obj);
		            } else if(obj.event === 'view'){
						cumstomObj.view(obj);
					}
		        });


		        form.on('switch(enabledState)', function(obj){

					//获取自定义标签valueId等上的值
					var switch_id = obj.elem.attributes['valueId'].nodeValue;
					var switch_ElementName = obj.elem.attributes['valueElementName'].nodeValue;
					// var switch_id = table.checkStatus('user-table');//表格id，获取选中行
					// var switch_id = obj.value;
					//do some ajax operations;
					var validFlag = Number(obj.elem.checked);//转为 0、1
					console.log(validFlag);
					$.ajax({
						url: "/one/element/local",
						type: "PUT",
						data:JSON.stringify({
							id:switch_id,
							elementName: switch_ElementName,
							status: validFlag
						}),
						dataType: "json",
						contentType: "application/json; charset=UTF-8",
						success: function(data){
							if (data.errorCode === '401') {
								loginStatusIntercept(data.msg)
								return
							}
							if(data.success){
								table.reload('user-table');
								console.log(obj.elem.checked);
								// obj.elem.checked = !obj.elem.checked;
								layer.msg('要素状态：'+ (obj.elem.checked ? '启用' : '禁用'), {
									icon : 1
								});
							}else{
								layer.msg("失败,失败原因:"+data.msg, {
									icon : 2
								});
								table.reload('user-table');
							}
						}
					});
					//  form.render('checkbox');
		        });

				form.on('submit(demo1)', function(data){

				});


		        cumstomObj.add = function(){
					$('#elementName').val("");//
				    $('#remark').val("");
					layer.open({
						type: 1,
						title: '添加业务要素',
						shade: 0.1,
						area: ['70%', '70%'],
						content: $('#service-window'),
						resize: true,
						btn: ['确定', '取消'],
						success:function(layero,index){
							$('#service-type').show();
							$('#service-address').show();
							$(".layui-upload-file").val("");
							$(".layui-upload-choose").html("");
							$(".layui-input.layui-unselect")[0].value="请选择"
							$( "#fm" )[0][2].value = ""
						},
						yes:function(index,layero){
							if(!$('#elementName').val()){
								layer.msg("请输入要素名称", {icon: 5});
								return;
							}

							var formData = new FormData($( "#fm" )[0]);

							var formMap=[];

							for(var pair of formData.entries()) {
								formMap[pair[0]]=pair[1];
							}

							if(!formMap["serviceType"]||formMap["file"].size<1){
								layer.msg("请选择要素类型或上传要素文件",{icon:2,time:1000});
								return;
							}

							let loading = layer.load();
							$.ajax({
								url: '/one/element/local',
								type:'POST',
								data:formData,
								async:false,
								cache:false,
								contentType: false,
								processData: false,
								success:function(result){
									if (result.errorCode === '401') {
										loginStatusIntercept(result.msg)
										return
									}
									layer.alert(JSON.stringify(result), {
										title: '最终的提交信息'
									});
									if(result.success){
										layer.msg(result.msg,{icon:1,time:1000},function(){
											layer.close(loading);
											layer.close(index);
											table.reload('user-table');
										});

									}else{
										layer.msg(result.msg,{icon:2,time:3000});
										layer.close(loading);
									}
								},
									error:function (err) {
										layer.msg("后台请求出错:"+err.responseText,{icon:2,time:1000});
										layer.close(loading);
								}
							})
						},

					});
				};
				// zip压缩包上传
			var uploadIns=	upload.render({ //允许上传的文件后缀
					elem: '#file',
					method: 'post', //可选项。HTTP类型，默认post
					url: postUrl, //改成您自己的上传接口
					accept: 'file', //普通文件
					exts: 'zip', //只允许上传压缩文件
					auto: false,
					size:512000,
					multiple: false,
					bindAction:"#commit",
					data:{},

					before: function(obj) {
						uploadfiles   = obj.pushFile();
						obj.preview(function(index, file, result){
							if(file.name.length > 0) {
								chooseFlag = true;
							}
						});
						this.data.elementName= $('#elementName').val();//     红色部分等同于 ajax 提交参数的效果 如 {"username":$("username").val()} 以此类推
						this.data.serviceType=$('#serviceType').val();
						this.data.remark=$('#remark').val();
						this.data.status = 1;
					},
					done: function(res){
						layer.msg('上传成功');
						console.log(res)
					}
				});
		        cumstomObj.edit = function(obj){
		            layer.open({
		                type: 1,
		                title: '修改',
		                shade: 0.1,
		                area: ['500px', '400px'],
		                content: '<div style="padding: 20px 100px;">'+ 99 +'</div>'
		            });
				}


				cumstomObj.view = function(obj){
					alert(12345);
					$.ajax({
						url: '/one/element/local/preview?id=10',
						dataType:'json',
						type:'get',
						success:function(result){
							if (result.errorCode === '401') {
								loginStatusIntercept(result.msg)
								return
							}
							if(result.success){
								console.log(result);
								layer.msg(result.msg,{icon:1,time:1000},function(){
									// obj.del();
								});
							}else{
								layer.msg(result.msg,{icon:2,time:1000});
							}
						}
					})
				}

		        cumstomObj.remove = function(obj){
		            layer.confirm('确认删除该要素吗？', {icon: 3, title:'提示'}, function(index){
		                layer.close(index);
		                let loading = layer.load();
		                $.ajax({
		                    url: MODULE_PATH+"remove/"+obj.data['userId'],
		                    dataType:'json',
		                    type:'delete',
							data:{ids:ids},
		                    success:function(result){
								if (result.errorCode === '401') {
									loginStatusIntercept(result.msg)
									return
								}
		                        layer.close(loading);
		                        if(result.success){
		                            layer.msg(result.msg,{icon:1,time:1000},function(){
		                                obj.del();
		                            });
		                        }else{
		                            layer.msg(result.msg,{icon:2,time:1000});
		                        }
		                    }
		                })
		            });
		        }

		        cumstomObj.batchRemove = function(obj){
		            let data = table.checkStatus(obj.config.id).data;
		            if(data.length === 0){
		                layer.msg("未选中数据",{icon:3,time:1000});
		                return false;
		            }
		            let ids = "";
		            for(let i = 0;i<data.length;i++){
		                ids += data[i].id+",";
		            }
		            ids = ids.substr(0,ids.length-1);
		            layer.confirm('确认删除该要素吗？', {icon: 3, title:'提示'}, function(index){
		                layer.close(index);
		                let loading = layer.load();
		                $.ajax({
		                    url: '/one/element/localDel',
		                    dataType:'json',
		                    type:'POST',
							data:{ids:ids},
		                    success:function(result){
								if (result.errorCode === '401') {
									loginStatusIntercept(result.msg)
									return
								}
		                        layer.close(loading);
		                        if(result.success){
		                            layer.msg(result.msg,{icon:1,time:1000},function(){
		                                table.reload('user-table');
		                            });
		                        }else{
		                            layer.msg(result.msg,{icon:2,time:1000});
		                        }
		                    }
		                })
		            });
		        }

		        cumstomObj.refresh = function(param){
		            table.reload('user-table');
		        }
		    })
		</script>
	</body>
</html>
